package com.bonc.ioc.validation;

import cn.hutool.core.util.StrUtil;
import com.bonc.ioc.common.util.AppReply;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author ：liyy
 * @date ：Created in 2020/3/24 17:25
 * @description：用于登录验证的切面
 * @modified By：
 * @version: V1.0
 */
@Aspect
@Component
public class AppAuthAnnotationAspect {

    @Autowired
    private HttpServletRequest request;

    public AppAuthAnnotationAspect() {

    }

    @Pointcut("@annotation(com.bonc.ioc.validation.AppAuthAnnotation)")
    public void controllerInteceptor() {
    }

    @Around("controllerInteceptor()")
    public Object before(ProceedingJoinPoint pjp) throws Throwable {
        //获取被注解的方法
        MethodInvocationProceedingJoinPoint mjp = (MethodInvocationProceedingJoinPoint) pjp;
        MethodSignature signature = (MethodSignature) mjp.getSignature();
        Method method = signature.getMethod();
        String tokenId = null;
        AppAuthAnnotation systemLogAnnotation = method.getAnnotation(AppAuthAnnotation.class);
        if (systemLogAnnotation != null) {
            tokenId = request.getHeader("p-user-token");
            System.out.println("tokenID +-----------------------" + tokenId);
            if (StrUtil.isEmpty(tokenId)) {
                return AppReply.error("403", "请登录后使用");
            }
        }

//        if (null == redisTemplate) {
//            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
//            redisTemplate = (RedisTemplate) factory.getBean("redisTemplate");
//        }

        //从缓存中读取登录信息
//        Object s = redisTemplate.opsForValue().get(tokenId);+
//        if (ObjectUtil.isNull(s)) {
//            return AppReply.error("无效的token，请重新登录");
//        }

        //TODO 判断是否在别处登录，通过比较IP的方式


        //如果没有报错,放行
        return pjp.proceed();
    }
}
